package com.avic.modules.backup4Dameng.vo;

import lombok.Getter;
import lombok.Setter;
import org.quartz.CronExpression;

import javax.validation.constraints.NotBlank;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@Getter
@Setter
public class BackupVo {

    private final static String DATE_FORMAT = "HH:mm";

    @NotBlank(message = "时间格式不对,格式为：HH:mm, 小于 23:59")
    private String backupTime;

    /**
     * @return 日期转换为 cronjob
     */
    public  String getCronExpression() {
        LocalTime time = LocalTime.parse(this.getBackupTime(), DateTimeFormatter.ofPattern(DATE_FORMAT));
        return "0 ".concat(time.format(DateTimeFormatter.ofPattern("mm HH * * ?")));
    }

    public void setBackupTime(String backupTime){
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(DATE_FORMAT);
        try{
            dtf.parse(backupTime);
            this.backupTime = backupTime;
        }catch (Exception ex){
            ex.printStackTrace();
            this.backupTime = null;
        }
    }

    public static String getTimeStrFromCronExpression(String cron) throws ParseException {
        CronExpression cronExpression = new CronExpression(cron);
        Date date = cronExpression.getNextValidTimeAfter(new Date());
        LocalDateTime dateTime = LocalDateTime.ofEpochSecond(date.getTime() / 1000L, 0, ZoneOffset.ofHours(8));
        String time = dateTime.format(DateTimeFormatter.ofPattern(DATE_FORMAT));
        return time;
    }

    /**
     * testing
     */
    public static void main(String[] args) throws ParseException {
        BackupVo backupVo = new BackupVo();
        backupVo.setBackupTime("19:20");
        System.out.println(backupVo.getBackupTime());
        System.out.println(backupVo.getCronExpression());
        // 需要转换的 cron 表达式
        String cron = backupVo.getCronExpression();
        CronExpression cronExpression = new CronExpression(cron);
        Date date = cronExpression.getNextValidTimeAfter(new Date());
        LocalDateTime dateTime = LocalDateTime.ofEpochSecond(date.getTime() / 1000L, 0, ZoneOffset.ofHours(8));
        String time = dateTime.format(DateTimeFormatter.ofPattern("HH:mm"));
        System.out.println(time);
    }

}
